public class Test01 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 方法一 迭代
     * @param
     * @return
     */

    /*public ListNode reverseList(ListNode head) {
        if (head == null){
            return head;
        }
        if (head.next == null){
            return head;
        }
        //定义一个变量记录头结点的下一个结点
        ListNode cur = head.next;
        //将头结点的 next 域置为空
        head.next = null;
        while (cur != null){
            //定义一个变量 记录 cur 的后继
            ListNode curNext = cur.next;
            cur.next = head;
            head = cur;
            cur = curNext;
        }
        return head;
    }*/


    /**
     * 利用递归
     * 看成一棵树，相当于后序遍历
     *
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        //链表为空
        if (head == null) {
            return head;
        }
        //链表的 next 域为空
        if (head.next == null) {
            return head;
        }
        //首先将后面的节点逆置
        //我相信你能帮我完成
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    public static void main(String[] args) {

    }
}
